﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xaml;
using System.CodeDom;
using System.Reflection;
using System.ComponentModel.Composition;

namespace NeuroSpeech.XamlExtensions
{
    [Export]
    public class NameWriter : XamlDirectiveWriter
    {

        public NameWriter():base(XamlLanguage.Name)
        {

        }


        #region public override void  WriteEndMember(XamlCodeContext context)
        public override void EndMember(XamlCodeContext context)
        {
            XamlItem Peek = context.Peek;
            string name = Peek.Value.Value as string;
            Peek.Name = name;

            CodeMemberField field = new CodeMemberField
            {
                Attributes = MemberAttributes.Family,
                Name = name,
                Type = new CodeTypeReference(Peek.Type.UnderlyingType)
            };

            Type type = Peek.Type.UnderlyingType;
            if (type != null) {
                PropertyInfo pname = type.GetProperty("Name");
                if (pname != null) {
                    CodeAssignStatement cas = new CodeAssignStatement { 
                        Left = Peek.TargetObject,
                        Right = new CodePrimitiveExpression(name)
                    };
                    context.Statements.Add(cas);
                }
            }


            context.Type.Members.Add(field);
        }
        #endregion


    }
}
